const { json } = require('body-parser')
const Commit = require('../utils/commit')
const commit = new Commit()
const moment = require('moment')


/**
 * description:查询卡密
 *
 * date_time: 2023-03-28 21:27:22
 * @author 冷筱宇 <209103572@qq.com>
 *
 * @param {string} card 卡密
 * @param {number} type 1:查询卡密是否被使用 2:查询卡密对应商品信息
*/
exports.checkCard = async (req, res) => {
    const card = req.query.card
    const type = req.query.type || 1
    if (card) {
        const cardResult = await commit.checkCard(card)
        if (cardResult.length) {
            let cardData = cardResult[0]
            if (cardData.state === 2) {
                if (cardData.oid !== -1) {
                    orderResult = await commit.checkOrder(cardData.oid)
                    console.log(orderResult[0]);
                    let orderData = orderResult[0]
                    let _s = {
                        1: '兑换成功!',
                        2: '兑换待处理!',
                        3: '兑换异常，请联系客服处理!',
                        4: '兑换处理中，请等待到账!'
                    }
                    let json = {
                        input: JSON.parse(orderData.input),
                        addtitm: moment(orderData.addtitm).format('YYYY-MM-DD HH:mm:ss'),
                        msg: _s[orderData.state]
                    }
                    return res.json({ code: 400, msg: '卡密已被使用', data: json, type: true })
                } else {
                    return res.json({ code: 400, msg: '卡密已作废', data: { addtime: '卡密已作废', input: ['卡密已作废'], msg: '卡密已作废' }, type: true })
                }

            } else {
                if (type == 1) {
                    return res.json({ code: 200, msg: '卡密未被使用', type: 1 })
                } else {
                    const cardGoods = JSON.parse(await commit.checkCardGoods(card))
                    console.log(cardGoods);
                    const GoodsData = {
                        name: cardGoods.data.name,
                        input: cardGoods.data.input
                    }
                    return res.json({ code: 200, msg: '获取成功', data: GoodsData, type: 2 })
                }
            }
        } else {
            return res.json({ code: 400, msg: '卡密错误', type: false })
        }
    } else {
        return res.json({ code: 400, msg: '卡密不能为空' })
    }
}

/**
 * description:兑换商品
 *
 * date_time: 2023-03-28 22:34:59
 * @author 冷筱宇 <209103572@qq.com>
 *
 * @param {string} card 卡密
 * @param {string} input 兑换信息数组
*/
exports.exchangeGoods = async (req, res) => {
    const { card, input } = req.body;
    if (card && input) {
        const inputData = { 0: input };
        const result = JSON.parse(await commit.exchangeGoods(card, inputData))
        if (result.code === 1) {
            return res.json({ code: 200, msg: "兑换成功，请等待到账" })
        } else {
            return res.json({ code: 400, msg: result.msg })
        }

    } else {
        return res.json({ code: 400, msg: '卡密或者兑换信息不能为空' })
    }
}

/**
 * description:获取当前系统内卡密数量
 *
 * date_time: 2023-04-08 20:54:26
 * @author 冷筱宇 <209103572@qq.com>
*/
exports.getCardNum = async (req, res) => {
    const result = await commit.getCardNum()
    return res.json({ code: 200, data: { total: result.total, used: result.used, unused: result.unused } })
}

/**
 * description:查询系统内卡密
 *
 * date_time: 2023-04-08 21:45:02
 * @author 冷筱宇 <209103572@qq.com>
*/
exports.getCardList = async (req, res) => {
    const type = req.query.state || 'all'
    const gid = req.query.gid
    const token = req.query.token || ''
    const { page = 1, limit = 15 } = req.query
    const result = await commit.getCardList(type, gid, token)
    // 把result里的addtime和endtime使用moment格式化为yyyy-mm-dd hh:mm:ss
    result.forEach(item => {
        item.addtime = moment(item.addtime).format('YYYY-MM-DD HH:mm:ss')
        if (item.state == 2) {
            item.state = '已使用'
            item.endtime = moment(item.endtime).format('YYYY-MM-DD HH:mm:ss')
        } else {
            item.state = '未使用'
            item.endtime = '未使用'
        }
    })
    // 将数据进行分页，page为当前页，limit为每页显示的条数
    const pageList = result.filter((u, index) => index < limit * page && index >= limit * (page - 1))

    return res.json({ code: 0, msg: '查询成功', count: result.length, data: pageList })
}

/**
 * description:删除卡密
 *
 * date_time: 2023-04-09 00:05:04
 * @author 冷筱宇 <209103572@qq.com>
*/
exports.delCard = async (req, res) => {
    const { id } = req.body
    if (id) {
        const result = await commit.delCard(id)
        if (result.affectedRows) {
            return res.json({ code: 200, msg: '删除成功' })
        } else {
            return res.json({ code: 400, msg: '删除失败' })
        }
    } else {
        return res.json({ code: 400, msg: 'id不能为空' })
    }
}

/**
 * description:批量删除卡密
 *
 * date_time: 2023-04-09 00:42:58
 * @author 冷筱宇 <209103572@qq.com>
 *
 * @param {Array} ids
*/
exports.delCardList = async (req, res) => {
    const ids = JSON.parse(req.body.ids)
    if (ids) {
        const result = await commit.delCardList(ids)
        if (result.affectedRows) {
            return res.json({ code: 200, msg: '删除成功' })
        } else {
            return res.json({ code: 400, msg: '删除失败' })
        }
    } else {
        return res.json({ code: 400, msg: 'id不能为空' })
    }

}

/**
 * description:批量生成卡密
 *
 * date_time: 2023-04-09 17:57:40
 * @author 冷筱宇 <209103572@qq.com>
*/
exports.addCardList = async (req, res) => {
    const { gid, num } = req.body
    if (gid && num) {
        // 判断商品是否存在，如果不存在则返回
        const goods = await commit.checkGoods(gid)
        if (!goods) return res.json({ code: 400, msg: '商品不存在' })
        // 如果生成数量为0则返回
        if (num == 0) return res.json({ code: 400, msg: '生成数量不能为0' })
        const { result, cardList } = await commit.addCardList(gid, num)
        if (result.affectedRows) {
            return res.json({
                code: 200, msg: '生成成功,共生成' + result.affectedRows + '张卡密', data: cardList
            })
        } else {
            return res.json({ code: 400, msg: '生成失败' })
        }
    } else {
        return res.json({ code: 400, msg: 'gid和num不能为空' })
    }
}
